<template>
  <div class="alert_download">
    <a-alert class="a-alert">
      <template #icon>
        <icon-exclamation-circle />
      </template>
      <div class="alert-item">合同生成后，修改租车费/续租费/换车费/租车押金/违章押金后，不影响已发起签署的合同金额。</div>
    </a-alert>
    <div class="download-button" v-permission="getPermission('batchdownload')" @click="downLoadAll({ orderCode: orderCode })">
      批量下载
    </div>
  </div>
  <table-index
    :table="tableCompulsory"
    @loadData="loadCompulsoryData"
    @selection-change="selectionChange"
    @pagenationChange="pagenationChange"
  >
    <template #contractStatus="{ record }">
      <div :class="'contract-statusname contract-statusname-' + record.contractStatus">{{ record.contractStatusName }}</div>
      <!-- 生成失败 -->
      <div v-if="record.contractStatus == -1" class="res-button" @click="errorShow(record)">原因</div>

      <!-- 签署中 -->
      <div v-if="record.contractStatus == 2">
        <!-- 承租方 -->
        <div class="status_copys">
          <div>承租方</div>
          <div v-if="record.lesseeSignStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.lesseeSignStatusName }}</div>
          <div v-if="record.lesseeSignStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.lesseeSignStatusName }}</div>
          <div
            v-if="record.lesseeSignStatus == 1"
            class="copy_link"
            v-permission="getPermission('contractCopySigningLink')"
            @click="getLesseeSignUrl(record)"
          >
            <img src="@/assets/link.png" />
            <span> 复制合同链接 </span>
          </div>
        </div>
        <!-- 出租方 -->
        <div class="status_copys">
          <div>出租方</div>
          <div v-if="record.hireSignStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.hireSignStatusName }}</div>
          <div v-if="record.hireSignStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.hireSignStatusName }}</div>
        </div>
      </div>

      <!-- 作废中 -->
      <div v-if="record.contractStatus == 7">
        <!-- 承租方 -->
        <div class="status_copys">
          <div>承租方</div>
          <div v-if="record.lesseeInvalidedStatus == 1" class="lessee_sign lessee_sign_status_1">
            {{ record.lesseeInvalidedStatusName }}
          </div>
          <div v-if="record.lesseeInvalidedStatus == 2" class="lessee_sign lessee_sign_status_2">
            {{ record.lesseeInvalidedStatusName }}
          </div>
          <div
            v-if="record.lesseeInvalidedStatus == 1"
            class="copy_link"
            v-permission="getPermission('contractCopyVoidLink')"
            @click="getLesseeSignUrl(record)"
          >
            <img src="@/assets/link.png" />
            <span> 复制作废链接 </span>
          </div>
        </div>
        <!-- 出租方 -->
        <div class="status_copys">
          <div>出租方</div>
          <div v-if="record.hireInvalidedStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.hireInvalidedStatusName }}</div>
          <div v-if="record.hireInvalidedStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.hireInvalidedStatusName }}</div>
        </div>
      </div>
    </template>
    <template #lessee="{ record }">
      <div v-if="record.leaseType == 1">{{ record.lesseeCompanyName }}</div>
      <div v-else>{{ record.lesseeName }}</div>
    </template>

    <template #createNode="{ record }">
      <div v-if="record.createWay == 1 && orderType == 1">{{ record.createNode }}</div>
      <div v-else-if="orderType == 2">{{ record.createNode }}</div>
      <div v-else>-</div>
    </template>
    <!-- 长租显示合同属性 -->
    <template #attribute v-if="orderType && orderType == 2">
      <div>合同属性</div>
    </template>
  </table-index>
  <!-- 维护 -->
  <maintenanceContract ref="maintenances" @ok="maintenanceFn" />
</template>
<script setup lang="ts">
  import clipboard3 from 'vue-clipboard3'
  import maintenanceContract from '@/views/order/short-order/detail/components/maintenance-contract.vue'

  import { ref, onMounted } from 'vue'
  import { useTable } from '@/hooks/table'
  import { signRecordAPI, getLesseeSignUrlAPI, getShortOrdrDetails, getSorderContractInfo } from '@/api/order/sOrder'
  import { getLongOrderDetails, getCzsContractInfo } from '@/api/order/czsOrder'
  import { Message, Modal } from '@arco-design/web-vue'
  import request from '@/api/axios.config'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'

  const { navigateTo } = useNavigate()
  const { toClipboard } = clipboard3()
  const orderCode = ref()
  const copyurl = ref() //复制承租方链接
  const maintenances = ref()
  const selectedRowKeys = ref([])
  const props = defineProps({
    orderId: Number,
    orderType: Number,
    contractAttribute: Number,
    permissionPrefix: String,
  })
  const userStore: any = useUserStore()
  userStore.setEpDetail()

  const selectionChange = (e: any) => {
    selectedRowKeys.value = e
  }

  // 传入的是后缀，拼接前缀+.+后缀
  const getPermission = (permissionSubfix: string) => {
    return props.permissionPrefix + '.' + permissionSubfix
  }

  // 页数选择后清空 复选框
  const pagenationChange = () => {
    selectedRowKeys.value = []
  }
  // 列表里点击失败原因
  const errorShow = (record: any) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      Modal.confirm({
        title: '提示',
        simple: true,
        hideCancel: true,
        okText: '关闭',
        content: record.createErrorReason,
      })
    }
  }
  // 去修改订单
  const toError = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '关闭',
      okText: '前往修改',
      content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
      onOk: () => {
        if (props.orderType == 1) {
          navigateTo(`/short-order/edit/${props.orderId}`, `${record.orderCode}-修改订单`)
        } else {
          navigateTo(`/long-order/edit/${props.orderId}`, `${record.orderCode}-修改订单`)
        }
      },
      onCancel: () => {
        loadCompulsoryData()
      },
    })
  }
  // 批量下载
  const downLoadAll = (record: any) => {
    console.log(record)
    if (selectedRowKeys.value.length) {
      console.log(selectedRowKeys.value)
      if (props.orderType == 1) {
        request
          .post(
            '/svmsContract/butchDownloadContractFile',
            {
              idList: selectedRowKeys.value,
            },
            {
              responseType: 'blob',
            }
          )
          .then((res) => {
            console.log(res)
            fileDownload(res.data, 'all', record)
          })
      } else {
        request
          .post(
            '/czsOrderInfo/butchDownloadContractFile',
            {
              idList: selectedRowKeys.value,
            },
            {
              responseType: 'blob',
            }
          )
          .then((res) => {
            console.log(res)
            fileDownload(res.data, 'all', record)
          })
      }
    } else {
      Message.warning('请勾选需要下载的合同')
    }
  }
  // 文件下载
  const fileDownload = (_res: any, tp: any, record: any) => {
    console.log(record)
    var name = ''
    var blob: any
    if (tp == 'all') {
      // 批量下载
      name = record.orderCode
      blob = new Blob([_res], { type: 'application/zip' })
    }
    if (tp == 'justone') {
      // 单个下载
      name = record.contractTypeName + record.contractNo
      blob = new Blob([_res], { type: 'application/pdf' })
    }
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) //创建下载的链接
    downloadElement.href = href
    // downloadElement.download = fileName; //下载后文件名
    downloadElement.download = name //下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
    window.URL.revokeObjectURL(href) //释放掉blob对象
  }

  // 数据
  const loadCompulsoryData = () => {
    var param

    // 长租
    param = {
      orderId: props.orderId,
      pageNumber: 1,
      pageSize: 1000,
      contractAttribute: props.contractAttribute,
    }

    tableCompulsory.tableLoading = true
    signRecordAPI(param)
      .then((res: any) => {
        // order.value = res.result
        const data = res.result //表
        data.forEach((i: any) => {
          if (i.contractStatus == 3 || i.contractStatus == 7 || i.contractStatus == 10) {
            i.disabled = false
          } else {
            i.disabled = true
          }
        })
        console.log('data', data)
        tableCompulsory.dataList = data
        if (tableCompulsory.dataList.length) {
          orderCode.value = tableCompulsory.dataList[0].orderCode
        }
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }
  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      // { title: '', slotName: 'selectkey', width: 120, fixed: 'left' },
      { title: '合同编号', dataIndex: 'contractNo', fixed: 'left', width: 240 },
      { title: '创建节点', dataIndex: 'createNode', slotName: 'createNode' }, //待修改
      { title: '合同类型', dataIndex: 'contractTypeName' },
      { title: '归属门店', dataIndex: 'siteName', width: 240 },
      { title: '合同状态', dataIndex: 'endTime', width: 300, slotName: 'contractStatus' },
      { title: '承租方', slotName: 'lessee' },
      { title: '出租方', dataIndex: 'tenantName' },
      { title: '发起人', dataIndex: 'startPersonName' },
      { title: '发起签署时间', dataIndex: 'startTime', width: 200 },
      { title: '发起节点', dataIndex: 'startNode' },
    ],
    tableLoading: false,
    operates: [
      {
        label: '编辑合同附件',
        width: 120,
        permission: getPermission('contractMaintenance'),
        show: (record: any) =>
          props.orderType == 2 && record.contractAttribute == 2 && (record.contractStatus == 10 || record.contractStatus == 11),
        method: (record: any) => {
          maintenances.value.show(record, props.orderId)
        },
      },
    ],
  })

  // 上传合同完成
  const maintenanceFn = () => {
    loadCompulsoryData()
  }
  // 快速复制
  const getLesseeSignUrl = (record: any) => {
    getLesseeSignUrlAPI({ id: record.id }).then((res: any) => {
      console.log(res)
      // 复制res.result
      copyurl.value = res.result
      toClipboard(copyurl.value)
      if (record.contractStatus == 2) {
        Message.success('承租方签署链接已复制到剪切板')
      }
      if (record.contractStatus == 7) {
        Message.success('承租方作废链接已复制到剪切板')
      }
    })
  }

  const orderDetails = ref()
  const viewContractInfo = ref()

  const getOrdersDetails = () => {
    if (props.orderType == 1) {
      getShortOrdrDetails({ id: props.orderId }).then((res: any) => {
        orderCode.value = res.result.orderInfo.orderCode
        orderDetails.value = res.result.orderInfo
        // orderCode.value = 'XC702022111500147'
        if (orderCode.value) {
          loadCompulsoryData()
        }
      })

      getSorderContractInfo({ id: props.orderId }).then((res: any) => {
        viewContractInfo.value = res.result.orderInfo
      })
    } else {
      getLongOrderDetails({ id: props.orderId }).then((res: any) => {
        orderDetails.value = {
          ...res.result.orderInfo,
          carLicenseNo: res.result.orderInfo.licenseNo,
          orderCode: res.result.orderInfo.orderNo,
          startTime: res.result.orderInfo.expectedUseCarTime,
          endTime: res.result.orderInfo.expectedReturnCarTime,
          rentDays: res.result.orderInfo.leaseNumberStr,
          carModelName: res.result.orderInfo.modelName,
          totalAmount: res.result.orderInfo.carRentAmount,
          carDeposit: res.result.orderInfo.carDepositAmount,
          illegalDeposit: res.result.orderInfo.violationDepositAmount,
          orderStatus: res.result.orderInfo.status,
        }
        loadCompulsoryData()
      })

      getCzsContractInfo({ id: props.orderId }).then((res: any) => {
        viewContractInfo.value = {
          ...res.result.orderInfo,
          carLicenseNo: res.result.orderInfo.licenseNo,
          orderCode: res.result.orderInfo.orderNo,
          startTime: res.result.orderInfo.expectedUseCarTime,
          endTime: res.result.orderInfo.expectedReturnCarTime,
          rentDays: res.result.orderInfo.leaseNumberStr,
          carModelName: res.result.orderInfo.modelName,
          totalAmount: res.result.orderInfo.carRentAmount,
          carDeposit: res.result.orderInfo.carDepositAmount,
          illegalDeposit: res.result.orderInfo.violationDepositAmount,
          orderStatus: res.result.orderInfo.status,
        }
      })
    }
  }
  onMounted(() => {
    // 获取企业联系人id
    if (props.orderId) {
      getOrdersDetails()
    }
  })
</script>
<style scoped lang="less">
  .alert_download {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
  }
  .create-contract {
    margin-left: 12px;
  }
  .download-button {
    display: inline-block;
    height: 32px;
    margin-left: 12px;
    line-height: 32px;
    padding: 0 15px;
    font-size: 14px;
    color: #fff;
    background-color: rgb(var(--primary-6));
    border: 1px solid transparent;
    cursor: pointer;
  }
  .res-button {
    display: inline-block;
    margin-top: 4px;
    padding: 0 8px;
    font-size: 12px;
    border-radius: 2px;
    color: #fff;
    background-color: rgb(var(--primary-6));
    border: 1px solid transparent;
    cursor: pointer;
  }
  .status_copys {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 4px;
  }
  .lessee_sign_status_1 {
    color: #ff7d00;
    border: 1px solid #ff7d00;
    background-color: #fff7e8;
    font-size: 12px;
    padding: 0 8px;
    border-radius: 2px;
  }
  .lessee_sign_status_2 {
    color: #00b42a;
    border: 1px solid #00b42a;
    background-color: #e8ffea;
    font-size: 12px;
    padding: 0 8px;
    border-radius: 2px;
  }
  .copy_link {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: #3491fa;
    text-decoration: underline;
    cursor: pointer;
    img {
      width: 20px;
      height: 20px;
    }
  }
  .contract-statusname {
    font-size: 14px;
    font-weight: 400;
  }
  .contract-statusname-1 {
    // 未发起
    color: #c7c7c7;
  }
  .contract-statusname-2 {
    // 签署中
    color: #3491fa;
  }
  .contract-statusname-3 {
    // 已完成
    color: #00b42a;
  }
  .contract-statusname-4 {
    // 已撤回
    color: #f53f3f;
  }
  .contract-statusname-5 {
    // 已撤回
    color: #f53f3f;
  }
  .contract-statusname-6 {
    // 已截止
    color: #f53f3f;
  }
  .contract-statusname-7 {
    // 作废中
    color: #ff7d00;
  }
  .contract-statusname-8 {
    // 已作废
    color: #f53f3f;
  }
  .contract-statusname-9 {
    // 无效
    color: #722ed1;
  }
  .contract-statusname--1 {
    // 生成失败
    color: #f53f3f;
  }
  .lessee_sign {
    margin: 0 8px 0;
  }
  .hire_sign {
    margin: 0 8px 0;
  }
  .a-alert {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    flex: 1;
  }
</style>
